package cn.virens.cmpt.server.handler;

import java.nio.ByteBuffer;
import java.nio.channels.CompletionHandler;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.virens.cmpt.server.channel.ChannelSimple;

public class ChannelReadHandler implements CompletionHandler<Integer, ByteBuffer> {
	private final Logger logger = LoggerFactory.getLogger(ChannelReadHandler.class);

	private final ChannelSimple channel;

	public ChannelReadHandler(ChannelSimple channel) {
		this.channel = channel;
	}

	@Override
	public void completed(Integer result, ByteBuffer readBuffer) {
		if (result != null && result > 0) {
			ByteBuffer buffer = readBuffer.duplicate();

			// 调用数据读取监听接口
			if (channel.getDataReadListener() != null) {
				channel.getDataReadListener().onRead(channel, buffer, result);
			}

			// 获取对应的连接通道的读操作线程，并放进去执行解码与解析
			channel.getChannelReadRunnable().offer(buffer);
			channel.getChannelReadRunnable().execute();

			// 重置读数据用的缓存buffer
			readBuffer.position(0);
			readBuffer.limit(readBuffer.capacity());

			// 重新开始读数据
			channel.getChannel().read(readBuffer, readBuffer, this);
		} else if (result != null && result == 0) {
			channel.getAcceptHandler().unbindUid(channel);
		} else if (result != null && result == -1) {
			channel.getAcceptHandler().unbindUid(channel); // 对方关闭连接
		} else if (result == null || result < 0) {
			channel.getAcceptHandler().unbindUid(channel);
		}
	}

	@Override
	public void failed(Throwable exc, ByteBuffer buffer) {
		if (channel.getDataErrorListener() != null) {
			channel.getDataErrorListener().onError(channel, buffer, exc);
		}
	}

}
